#include "MainWidget.h"
#include "Reader.h"
#include "Writer.h"
#include "LibraryWidget.h"
#include <QVBoxLayout>
#include <QThreadPool>
#include <QList>
#include <QMutexLocker>
#include <QPainter>


MainWidget::MainWidget(QWidget *parent) :
	QWidget(parent)
{
	library = new Library(maxBooksNumber);
	QList<Reader*> readers;
	for (int i = 0; i < readersNumber; i++) {
		readers.append(new Reader(library, readingTime));
	}

	QList<Writer*> writers;
	for (int i = 0; i < writersNumber; i++) {
		writers.append(new Writer(writingTime, editTime, library));
	}

	QProgressBar *booksNumberProgress = new QProgressBar(this);
	booksNumberProgress->setMaximum(maxBooksNumber);
	booksNumberProgress->setValue(0);
	booksNumberProgress->setFormat("%v");
	connect(library, SIGNAL(freeBooksNumberChanged(int)), booksNumberProgress, SLOT(setValue(int)));

	activeThreadsProgress = new QProgressBar(this);
	activeThreadsProgress->setMaximum(readersNumber + writersNumber);
	activeThreadsProgress->setFormat("%v");
	activeThreadsProgress->setValue(readersNumber + writersNumber);

	waitingThreadsProgress = new QProgressBar(this);
	waitingThreadsProgress->setMaximum(readersNumber + writersNumber);
	waitingThreadsProgress->setValue(0);
	waitingThreadsProgress->setFormat("%v");

	connect(library, SIGNAL(activate()), this, SLOT(increaseActive()));
	connect(library, SIGNAL(deactivate()), this, SLOT(increaseWaiting()));

	LibraryWidget *lw = new LibraryWidget(maxBooksNumber);
	connect(library, SIGNAL(freeBook(int)), lw, SLOT(freeBook(int)));
	connect(library, SIGNAL(readBook(int)), lw, SLOT(readBook(int)));
	connect(library, SIGNAL(editBook(int)), lw, SLOT(editBook(int)));

	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->addWidget(lw);
	mainLayout->addWidget(booksNumberProgress);
	mainLayout->addWidget(activeThreadsProgress);
	mainLayout->addWidget(waitingThreadsProgress);

	setLayout(mainLayout);


	foreach (Writer *writer, writers) {
		threadPool.start(writer);
	}

	foreach (Reader *reader, readers) {
		threadPool.start(reader);
	}
}

void MainWidget::increaseActive()
{
	QMutexLocker locker(&mutex);
	activeThreadsProgress->setValue(activeThreadsProgress->value() + 1);
	waitingThreadsProgress->setValue(waitingThreadsProgress->value() - 1);
}

void MainWidget::increaseWaiting()
{
	QMutexLocker locker(&mutex);
	activeThreadsProgress->setValue(activeThreadsProgress->value() - 1);
	waitingThreadsProgress->setValue(waitingThreadsProgress->value() + 1);
}
